package com.example.vue.account.util;

import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.util.Random;

/**
 * @description 账户常用的工具类
 * @Author longdeng
 * @Date 2020/5/17 0017 9:10
 */
public class AccountUtil {


    /**
     * @param password 密码
     * @param salt     盐值
     *                 password encryption
     * @return
     * @description 密码加密
     */
    public static String EncoderByMd5(String password, String salt) throws Exception {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        //加密后的字符串
        String newPassword = base64en.encode(md5.digest((password + salt).getBytes("utf-8")));
        return newPassword;
    }

    /**
     * @param length 盐值长度
     * @return
     * @description 获取随机盐值
     */
    public static String getSalt(int length) throws Exception {
        if (length <= 0) {
            throw new Exception("AccountUtil 工具类入参不合法");
        }
        StringBuffer sb = new StringBuffer();
        String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        for (int i = 0; i < length; i++) {
            sb.append(str.charAt(new Random().nextInt(str.length())));
        }
        return sb.toString();
    }

}
